package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

	// 注入DAO
	@Autowired
	private CustomerRepository customerRepository;

	//查询所有未关联用户
	@Override
	public List<Customer> findNoAssociationCustomers() {
		// fixedAreaId is null
		return customerRepository.findByFixedAreaIdIsNull();
	}
 
	//根据定区id查询已关联的客户
	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(
			String fixedAreaId) {
		// fixedAreaId is ?
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}
	
	 //关联客户到定区 把传过来用户的id字符串切割成单个customer id,在调用dao层修改方法
	//把改客户的定区列由null修改为传过来的定区的id
	@Override
	public void associationCustomersToFixedArea(String customerIdStr,
			String fixedAreaId) {
		// 解除关联动作 先把改定区id对应的客户中的定区id都要置为null 下面传过来了多少要关联的客户 再进行一次修改
		customerRepository.clearFixedAreaId(fixedAreaId);

		// 切割字符串 1,2,3
		if (StringUtils.isBlank(customerIdStr) || "null".equals(customerIdStr)) {
			return;
		}
		String[] customerIdArray = customerIdStr.split(",");
		for (String idStr : customerIdArray) {
			System.out.println("客户的id是"+idStr);
			//把字符串id转换成Integer
			Integer id = Integer.parseInt(idStr);
			//调用DAO层修改方法
			customerRepository.updateFixedAreaId(fixedAreaId, id);
		}
	}

	@Override
	public void regist(Customer customer) {
	      customerRepository.save(customer);
	}

	
	
	@Override
	public Customer findByTelephone(String telephone) {
		// TODO Auto-generated method stub
		return customerRepository.findByTelephone(telephone);
	}

	@Override
	public void updateType(String telephone) {
		   customerRepository.updateType(telephone);
		
	}

	
	//用户登录功能
	@Override
	public Customer login(String telephone, String password) {
		return customerRepository.findByTelephoneAndPassword(telephone,
				password);
	}

	@Override
	public String findFixedAreaIdByAddress(String address) {
		return customerRepository.findFixedAreaIdByAddress(address);
	}


	
 

}
